package 链表;

import Utils.ListNode;

import java.util.ArrayList;

/**
 * @author: TTDB
 * @create: 2025/9/16
 */
public class sortList {
    // 现有方法的小优化
    public ListNode sortListEasy(ListNode head) {
        if (head == null) return null;

        // 使用ArrayList排序的方法（已有）
        ArrayList<Integer> list = new ArrayList<>();
        ListNode current = head;
        while(current != null){
            list.add(current.val);
            current = current.next;
        }

        list.sort(null);

        // 复用原链表节点，避免创建新节点
        current = head;
        for(int val : list) {
            current.val = val;
            current = current.next;
        }

        return head;
    }

    public ListNode sortList(ListNode head) {
        // 归并排序实现 - 更优解法
        if (head == null || head.next == null) {
            return head;
        }

        // 快慢指针找中点
        ListNode slow = head, fast = head, prev = null;
        while (fast != null && fast.next != null) {
            prev = slow;
            slow = slow.next;
            fast = fast.next.next;
        }

        // 断开链表
        prev.next = null;

        // 递归排序两部分
        ListNode l1 = sortList(head);
        ListNode l2 = sortList(slow);

        // 合并两个有序链表
        return merge(l1, l2);
    }

    private ListNode merge(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode cur = dummy;

        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                cur.next = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }

        // 连接剩余节点
        if (l1 != null) cur.next = l1;
        if (l2 != null) cur.next = l2;

        return dummy.next;
    }
}
